package cn.scut.post.controller;

import cn.scut.post.pojo.Post;
import cn.scut.post.service.impl.PostInfoService;
import cn.scut.post.utils.Model;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/post/info")
public class PostInfoController {
    PostInfoService postInfoService;

    //用户发布帖子
    @PutMapping("/upload")
    public Model apiUpload(@RequestBody Post post) {
        Post temp = postInfoService.uploadPost(post);
        return new Model(true, temp, "帖子成功保存");
    }

    //获取某个用户自己已发布过的帖子
    @GetMapping("/download")
    public Model apiDownload(@RequestBody JSONObject jsonObject) {
        String openid = jsonObject.getString("openid");
        List<Post> posts = postInfoService.downloadPost(openid);
        if (posts != null) return new Model(true, posts, "用户已发表帖子成功获取");
        else return new Model(false, null, "该用户还未发表过帖子");
    }

    //删除某个用户自己指定的某个帖子
    @DeleteMapping("/delete")
    public Model apiDelete(@RequestBody JSONObject jsonObject) {
        String postid = jsonObject.getString("postid");
        int i = postInfoService.deletePost(postid);
        if (i > 0) {
            return new Model(true, true, "帖子删除成功");
        } else {
            return new Model(false, false, "帖子删除失败");
        }
    }

    //获取数据库中的所有帖子
    @GetMapping("/getAll")
    public Model apiGetAllPost() {
        List<Post> list = postInfoService.list();
        if (list != null) {
            return new Model(true, list, "所有帖子信息如下");
        } else {
            return new Model(false, null, "未知错误");
        }
    }

    @Autowired
    public void setPostInfoService(PostInfoService postInfoService) {
        this.postInfoService = postInfoService;
    }
}
